import requests
from lxml import etree
from selenium import webdriver
from selenium.webdriver.common.by import By
from config.gp_config import DriverConfig


class Base:

    def __init__(self):
        self.session = requests.Session()

    def request(self, url, encoding='gbk'):
        resp = self.session.get(url, verify=False)
        if encoding:
            resp.encoding = encoding
        if resp.status_code != 200:
            return resp.status_code
        return resp

    def parse(self, html, xpath):
        return etree.HTML(html).xpath(xpath)

    def output(self, url, xpath):
        return self.parse(self.request(url).text, xpath)


class Driver:

    def __init__(self):
        self.env = DriverConfig.driver_env
        self.driver_path = DriverConfig.driver_path
        self.driver = self.create_dr(self.env)


    def create_dr(self, dr_type):
        if dr_type == "chrome":
            from selenium.webdriver.chrome.options import Options
            # from selenium.webdriver.chrome.service import Service
            # from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
            # desired_capabilities = DesiredCapabilities.CHROME
            # desired_capabilities["pageLoadStrategy"] = "none"
            opt = Options()
            opt.add_argument("--headless")
            opt.add_argument("--disable-gpu")
            opt.add_argument("--no-sandbox")
            # opt.page_load_strategy = 'none'
            dr = webdriver.Chrome(options=opt)
        if dr_type == "edge":
            from selenium.webdriver.edge.options import Options
            opt = Options()
            opt.add_argument("--headless")
            opt.add_argument("--disable-gpu")
            dr = webdriver.Edge(options=opt)
        return dr

    def get(self, url):
        self.driver.get(url)
        self.driver.implicitly_wait(3)

    def get_page(self):
        return self.driver.page_source

    def get_title(self):
        return self.driver.title

    def get_element_id(self, id):
        return self.driver.find_element(By.ID, id)

    def get_element_class(self, class_name):
        return self.driver.find_element(By.CLASS_NAME, class_name)

    def get_element_xpath(self, xpath):
        return self.driver.find_element(By.XPATH, xpath)

    def get_elements_xpath(self, xpath):
        return self.driver.find_elements(By.XPATH, xpath)

    def close(self):
        self.driver.quit()


if __name__ == '__main__':
    bb = Driver()
    bb.get("https://www.baidu.com")
    print(bb.get_title())
